package com.puboot.common.config;

import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.protocol.HttpContext;
import org.elasticsearch.client.RestClientBuilder;
import org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchRestClientProperties;
import org.springframework.boot.autoconfigure.elasticsearch.RestClientBuilderCustomizer;
import org.springframework.boot.context.properties.PropertyMapper;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.TimeUnit;

/**
 * Created by kk on 2020/8/25.
 */
@Configuration
public class CMSRestClientBuilderCustomizer implements RestClientBuilderCustomizer {

    private static final PropertyMapper map = PropertyMapper.get();

    private final ElasticsearchRestClientProperties properties;

    CMSRestClientBuilderCustomizer(ElasticsearchRestClientProperties properties) {
        this.properties = properties;
    }

    @Override
    public void customize(RestClientBuilder builder) {
    }

    @Override
    public void customize(HttpAsyncClientBuilder builder) {
        builder.setKeepAliveStrategy(CustomConnectionKeepAliveStrategy.INSTANCE);
    }

    @Override
    public void customize(RequestConfig.Builder builder) {
    }



     static class CustomConnectionKeepAliveStrategy extends DefaultConnectionKeepAliveStrategy {

        public static final CustomConnectionKeepAliveStrategy INSTANCE = new CustomConnectionKeepAliveStrategy();

        private CustomConnectionKeepAliveStrategy() {
            super();
        }

        /**
         * 最大keep alive的时间（分钟）
         * 这里默认为10分钟，可以根据实际情况设置。可以观察客户端机器状态为TIME_WAIT的TCP连接数，如果太多，可以增大此值。
         */
        private final long MAX_KEEP_ALIVE_MINUTES = 20;

        @Override
        public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
            long keepAliveDuration = super.getKeepAliveDuration(response, context);
            // <0 为无限期keepalive
            // 将无限期替换成一个默认的时间
            if(keepAliveDuration < 0){
                return TimeUnit.MINUTES.toMillis(MAX_KEEP_ALIVE_MINUTES);
            }
            return keepAliveDuration;
        }
    }
}
